package com.xy.generate.generator;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class ScriptGenerator {
    public static void doGenerate(String outputPath, String jarPath) {
        String osOperator = System.getProperty("os.name");
        //判断当前系统是linux还是Windows
        //written script
        //// Linux
        StringBuilder stringBuilder = new StringBuilder();
        if (osOperator.contains("Linux") || osOperator.contains("linux")) {
            //// 写入注释内容
            stringBuilder.append("#!/bin/bash").append("\n");
            stringBuilder.append(String.format("java -jar %s \"$@\"", jarPath)).append("\n");
            //生成可执行文件文件
            FileUtil.writeBytes(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), outputPath);
            //添加可执行权限
            try {
                Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
                Files.setPosixFilePermissions(Paths.get(outputPath), permissions);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (osOperator.contains("Windows") || osOperator.contains("windows")) {
            //windows
            stringBuilder = new StringBuilder();
            stringBuilder.append("@echo off").append("\n");
            stringBuilder.append(String.format("java -jar %s %%*", jarPath)).append("\n");
            FileUtil.writeBytes(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), outputPath + ".bat");
            System.out.println("生成脚本成功");
        }
    }

    public static void main(String[] args) {
        String outputPath = System.getProperty("user.dir") + File.separator + "generated" + File.separator + "acm-template-pro-generate" + File.separator + "generatorScript";
        doGenerate(outputPath, "acm-template-pro-generate-1.0-jar-with-dependencies.jar");
    }
}
